package com.taofuxn.yycreazy.rxjava;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 自定义net回调观察者
 * Created by wanghuafu on 16/9/16.
 */
public class SubscriberCallback<T> extends Subscriber<T> {

    private ApiCallback<T> mApiCallback;

    public SubscriberCallback(ApiCallback<T> mApiCallback){
        this.mApiCallback = mApiCallback;
    }

    @Override
    public void onCompleted() {
        mApiCallback .onCompleted();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            String msg = httpException.getMessage();
            if (code == 504) {
                msg = "网络不给力";
            }
            mApiCallback.onFailed(code, msg);
        } else {
            mApiCallback.onFailed(0, e.getMessage());
        }
        mApiCallback.onCompleted();
    }

    @Override
    public void onNext(T t) {
        mApiCallback.onSuccess(t);
    }
}
